private package fhq.hcmute.edu.vn.event;

import java.awt.AWTException;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.InputEvent;

class MouseEvent {
	public static final int MOUSE_LEFT = InputEvent.BUTTON1_MASK;
	public static final int MOUSE_RIGHT = InputEvent.BUTTON3_MASK;
	public static final int MOUSE_WHEEL = InputEvent.BUTTON2_MASK;

	private Robot robot;
	private float xLeftover = 0;
	private float yLeftover = 0;
	private Rectangle[] gBounds;

	public MouseEvent() {
		try {
			robot = new Robot();
			GraphicsDevice[] gDevices = GraphicsEnvironment
					.getLocalGraphicsEnvironment().getScreenDevices();
			int l = gDevices.length;
			gBounds = new Rectangle[l];
			for (int i = 0; i < l; ++i) {
				gBounds[i] = gDevices[i].getDefaultConfiguration().getBounds();
			}
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void leftClick() {
		robot.mousePress(MOUSE_LEFT);
	}

	public void rightClick() {
		robot.mousePress(MOUSE_RIGHT);
	}

	public void leftRelease() {
		robot.mouseRelease(MOUSE_LEFT);
	}

	public void rightRelease() {
		robot.mouseRelease(MOUSE_RIGHT);
	}

	// public void doubleClick() {
	// leftClick();
	// leftClick();
	// }

	public void wheelClick() {
		robot.mousePress(MOUSE_WHEEL);
		robot.mouseRelease(MOUSE_WHEEL);
	}

	public void mouseScrollUp(int sensitivity) {
		robot.mouseWheel(-sensitivity);
		robot.delay(50);
	}

	public void mouseScrollDown(int sensitivity) {
		robot.mouseWheel(sensitivity);
		robot.delay(50);
	}

	public void mouseMove(final float xOffset, final float yOffset) {
		PointerInfo info = MouseInfo.getPointerInfo();
		if (info != null) {
			Point p = info.getLocation();
			// for sub-pixel mouse accuracy, save leftover rounding value
			float ox = (xOffset) + xLeftover;
			float oy = (yOffset) + yLeftover;
			int ix = Math.round(ox);
			int iy = Math.round(oy);

			xLeftover = ox - ix;
			yLeftover = oy - iy;

			p.x += ix;
			p.y += iy;
			int l = gBounds.length;
			for (int i = 0; i < l; ++i) {
				if (gBounds[i].contains(p)) {
					robot.mouseMove(p.x, p.y);
					break;
				}
			}

			try {
				robot.mouseMove(p.x, p.y);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
}
